﻿package com.ease.flex.remoting
{
	import com.ease.util.RemoteService;
	import com.ease.util.ServiceUtil;
	import com.ease.util.events.MethodReturnEvent;
	import com.ease.framework.CallbackUtil;
	import com.obas.flex.common.event.SessionTimeoutEvent;
	import com.obas.flex.common.util.ClientErrorUtil;

	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.external.ExternalInterface;

	import mx.managers.BrowserManager;
<#if remotingDestinationClassList ??>
<#list remotingDestinationClassList as t>
	import ${t.name};
</#list>
</#if>

	public class ${className} {

		private static var _instance:${className} = null;

		public function ${className}(singleton:SingletonClass) {
			var contextPath:String = ExternalInterface.call("BrowserHistory.getURL");
			RemoteService.defaultChannelUri = ServiceUtil.getDefaultChannelUri(contextPath);
		}

		public static function onOperationReturn(eventDispatcher:EventDispatcher, event:MethodReturnEvent):void {
	    	//var response:Event = null;
			//response = CallbackUtil.createResponseFromRequest(event.callContext, event.result, event.error);
			//eventDispatcher.dispatchEvent(response);
			
			var response:Event = null;
         	//Session timeout
         	if( null != event.error && ClientErrorUtil.getErrorType(event.error) == ClientErrorUtil.AUTHENTICATION_ERROR) {
            	var sessionTimeoutEvent:SessionTimeoutEvent = new SessionTimeoutEvent(SessionTimeoutEvent.SESSION_TIMEOUT);
            	eventDispatcher.dispatchEvent(sessionTimeoutEvent);
            	response = CallbackUtil.createResponseFromRequest(event.callContext, null, null);
         	} else {
            	response = CallbackUtil.createResponseFromRequest(event.callContext, event.result, event.error);
         	}
         	eventDispatcher.dispatchEvent(response);
		}

	    public static function getInstance():${className} {
	        if (_instance == null) {
				_instance = new ${className}(new SingletonClass());
	        }

	        return _instance;
	    }
<#if remotingDestinationClassList ??>
<#list remotingDestinationClassList as t><#assign sn = t.simpleName><#assign un = uncapitalize(sn)>
		private var _${un}:${sn} = null;

		public static function get${sn}():${sn} {
			if (getInstance()._${un} == null) {
				getInstance()._${un} = new ${sn}();
			}
			return getInstance()._${un};
		}

		public function set enabled${sn}(value:Boolean):void {
			if (getInstance()._${un}) {
				getInstance()._${un}.enabled = value;
			}
		}
</#list>

</#if>
	}
}
class SingletonClass{}
